using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    /// <summary>
    /// Store Word
    /// </summary>
    public class Sw : MemoryAccessInstruction
    {
        public override int CycleCount
        {
            get { return 1; }
        }

        public Sw()
            : base("sw")
        {
        }

        private uint memory;
        private uint address;

        /// <summary>
        /// Stores the contents of register rD, into the word aligned memory 
        /// location that results from adding the contents of registers rA and rB.
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            address =
              MicroblazeComponent.ReadRegister(SourceRegisterA) +
              MicroblazeComponent.ReadRegister(SourceRegisterB);

            address &= 0xFFFFFFFC;
            memory = MicroblazeComponent.ReadRegister(DestinationRegister);

            WriteWordTransaction transaction = new WriteWordTransaction(MicroblazeComponent, address, memory);
            MicroblazeComponent.BeginDataTransaction(transaction);

            while (transaction.Status != Transaction.TransactionStatus.Complete)
                MicroblazeComponent.WaitOneCycle();            
        }

        public override string ToString()
        {
            return string.Format("sw r{0}, r{1}, r{2}",
              DestinationRegister,
              SourceRegisterA,
              SourceRegisterB
            );
        }
    }
}
